<template>
    <div class="header">
        <van-icon @click="goBack" name="arrow-left" style="margin:0 .3rem 0 0;" />编辑收货地址页面
    </div>
    <van-address-edit
        :area-list="areaList"
        show-postal
        show-delete
        show-set-default
        show-search-result
        :search-result="searchResult"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
        @delete="onDelete"
        @change-detail="onChangeDetail"
        :address-info="addressInfo.arr"
    />
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { ref, reactive } from 'vue';
import { Toast } from 'vant';
import { areaList } from '@vant/area-data';
import requestFn from '@/utils/https';
const router = useRouter()

// 回到上一页
const goBack = () => {
    router.push({
        path: '/addressItem'
    })
}

// 接受参数
const route = useRoute()
const addressId = route.query.addId
// console.log(addressId)

// 地址信息，初始值
let addressInfo = reactive({ 
    arr: [] 
})

// 页面一打开，就根据传入的id，获得相应的地址信息
requestFn({
    url: '/mysql_getIdAddress',
    method: 'get',
    data: { n: addressId }
}).then( res => {
    // console.log(res);
    let _temp = res.data[0]
    _temp.isDefault = JSON.parse(_temp.isDefault) === 1 ? true : false 
    // _temp.postalCode = "" + _temp.postalCode
    addressInfo.arr = _temp
    // console.log(addressInfo.arr)
})

const onSave = (obj) => {
    console.log(obj)
    // console.log(obj.name)
    obj.isDefault = obj.isDefault === true ? 1 : 0

    requestFn({
        url: '/mysql_updateAddress',
        method: 'get',
        data: { n: addressId, m: obj}
    }).then( res => {
        // 修改用户地址成功，跳转到地址列表页
        if(res.data.is){
            router.push({
                path:'/addressItem'
            })
        }
    })
}
const onDelete = () => Toast('delete');
const searchResult = ref([]);
const onChangeDetail = (val) => {
    if (val) {
        searchResult.value = [
            {
                name: '黄龙万科中心',
                address: '杭州市西湖区',
            },
        ];
    } else {
        searchResult.value = [];
    }
}

</script>

<style lang="less" scoped>
.header {
    margin: 0 .5rem;
    height: 1rem;
    padding: .2rem 0;
    text-align: left;
    font-size: .6rem;
}
</style>
